//
//  UIScreenExtension.swift
//  AFNetworking
//
//  Created by Max on 2019/7/26.
//

import UIKit

public extension UIScreen {
    
    /// main screen width
    static var width: CGFloat {
        return self.main.bounds.width
    }
    
    /// main screen height
    static var height: CGFloat {
        return self.main.bounds.height
    }
    
    /// 1.0/main screen scale
   static var onePixel: CGFloat {
        return 1.0/self.main.scale
    }

    /// main screen width/375.0
    static var widthRatioToDesignScreen: CGFloat {
        return self.width/375.0
    }
    
    static var keyWindow: UIWindow? {
        let keyWindow = UIApplication.shared.connectedScenes
                .filter({$0.activationState == .foregroundActive})
                .map({ $0 as? UIWindowScene })
                .compactMap({ $0 })
                .first?.windows
                .first(where: { $0.isKeyWindow })
        return keyWindow
    }
    
    /// topViewController for Window
    static var topViewController: UIViewController? {
        
        var result = UIScreen.keyWindow?.rootViewController
        while true {
            if let navController = result as? UINavigationController {
                result = navController.visibleViewController
            } else if let tabController = result as? UITabBarController {
                result = tabController.selectedViewController
            } else if let presentController = result?.presentedViewController {
                result = presentController
            } else {
                break
            }
        }
        return result
    }
}
